package impl

import (
	"context"
	"encoding/json"
	"github.com/redis/go-redis/v9"
)

type DictServiceCacheProxy struct {
	rdb redis.UniversalClient
	*DictServiceImpl
}

func NewDictServiceCacheProxy(rdb redis.UniversalClient, dictServiceImpl *DictServiceImpl) *DictServiceCacheProxy {
	return &DictServiceCacheProxy{rdb: rdb, DictServiceImpl: dictServiceImpl}
}

func (s *DictServiceCacheProxy) Options(key string, language string) []map[string]interface{} {
	ctx := context.Background()
	redisKey := "gorm:dict_service_cache:options"
	if ok := s.rdb.HExists(ctx, redisKey, key).Val(); ok {
		if bytes, err := s.rdb.HGet(ctx, redisKey, key).Bytes(); err == nil {
			var mm []map[string]interface{}
			if err := json.Unmarshal(bytes, &mm); err == nil {
				return mm
			}
		}
	}
	options := s.DictServiceImpl.Options(key, language)
	if marshal, err := json.Marshal(options); err == nil {
		s.rdb.HSet(ctx, redisKey, key, string(marshal))
	}
	return options
}
